/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author user
 */
import javax.swing.*;
import javax.swing.table.*;
import java.sql.*;
import java.awt.*;
import java.awt.event.*;

public class InsertJTableDatabase{
JTable table;
JButton button;


public static void main(String[] args) 
    {

    new InsertJTableDatabase();

    }

public InsertJTableDatabase(){

    JFrame frame = new JFrame("Getting Cell Values in JTable");
    JPanel panel = new JPanel();
    String data[][] = {{"Angelina","Mumbai"},{"Martina","Delhi"},{"1","2"}};

    String col[] = {"Name","Address"};
    DefaultTableModel model = new DefaultTableModel(data, col);
    table = new JTable(model);
    JScrollPane pane = new JScrollPane(table);
    button=new JButton("Submit");

    button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae){
    PreparedStatement pstm = null;
    ResultSet rs;
    int index=0;
    int count=table.getRowCount();
    System.out.println(count);

try{
//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            String url = "jdbc:mysql://127.0.0.1:3306/dase_1251";
            String username = "root";
            String password = "123456";
            Connection connect = DriverManager.getConnection(url,username,password);
for(int i=0;i<count;i++){
Object obj1 = GetData(table, i, 0);
Object obj2 = GetData(table, i, 1);
String value1=obj1.toString();
String value2=obj2.toString();

System.out.println(value1);
System.out.println(value2);

pstm=connect.prepareStatement("insert into jtable_to_db values(?,?)");
pstm.setString(1,value1);
pstm.setString(2,value2);

pstm.executeUpdate();

index++;
}

}
catch(Exception e){}
}
});
panel.add(pane);
panel.add(button);
frame.add(panel);
frame.setSize(500,500);
frame.setUndecorated(true);
frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public Object GetData(JTable table, int row_index, int col_index){
return table.getModel().getValueAt(row_index, col_index);
}
}
